package com.fulin.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 字符串转换为数字,这里用到了自动状态机的方法
 * @Author fulin16
 * @Date 2020/10/22 10:19
 **/
public class Num8 {

    public static void main(String[] args) {

    }

    private static int index(char c){
        if(c == ' ') return 0;
        if(c == '+' || c == '-') return 1;
        if(Character.isDigit(c)) return 2;
        return 3;
    }
    private static int sign = 1;
    private static long res = 0;

    public static int transfer(String s){
        for(int i = 0 ; i < s.length();i++){
            char c = s.charAt(i);
            status =  map.get(status)[index(c)];
            if(status == STATUS.D){
                //数字
                res = res * 10 + c - '0'; //注意这里的 c - '0',因为char是数字那么 c - '0' 之后就是
                res = sign == 1 ? Math.min(res,(long)Integer.MAX_VALUE) : Math.max(res,(long)Integer.MIN_VALUE);
            }else if(status == STATUS.S){
                if(c == '-'){
                    sign = -1;
                }
            }
        }
        return (int)(sign * res);
    }

    private static enum STATUS{
        B,      //开始 ("")
        S,      //符号（+,-）
        D,      //数字
        E;      //其他
    }
    private static Map<STATUS,STATUS[]> map = new HashMap<STATUS,STATUS[]>();

    private static STATUS status = STATUS.B;

    static{
        map.put(STATUS.B, new STATUS[]{STATUS.B, STATUS.S, STATUS.D, STATUS.E});
        map.put(STATUS.S, new STATUS[]{STATUS.E, STATUS.E, STATUS.D, STATUS.E});
        map.put(STATUS.D, new STATUS[]{STATUS.E, STATUS.E, STATUS.D, STATUS.E});
        map.put(STATUS.E, new STATUS[]{STATUS.E, STATUS.E, STATUS.E, STATUS.E});
    }


}
